<template>
	<view class="login content">
		<uni-title type="h1" title="你好，欢迎使用超级抵现卡!" color="#fff" align="center"></uni-title>
		<uni-popup ref="popup" background-color="#fff">
			<view class="popup-content" :class="{ 'popup-height': type === 'left' || type === 'right' }">
				<!-- <button @click="close">关闭</button> -->
				<text class="text">
					超级门店赋能系统用户协议
					<rich-text :nodes="service_txt" class="text"></rich-text>
				</text>
			</view>
		</uni-popup>
		<uni-popup ref="popup2" background-color="#fff">
			<view class="popup-content" :class="{ 'popup-height': type === 'left' || type === 'right' }">
				<text class="text">
					隐私政策
					<rich-text :nodes="privacy_txt" class="text"></rich-text>
				</text>
			</view>
		</uni-popup>
		<view class="fixed-btn">
			<button type="primary" @click="wxlogin" class="">微信一键登录</button>
			<radio-group name="radio" @change="changeradio">
				<label>
					<view class="uni-flex uni-row policy-text">
						<view class="flex-item"><radio :checked="readitem" color="#4371FA"/></view>
						<view class="flex-item font-baise">我已阅读并同意<text class="font-blue" @click="toggle('bottom')">《用户协议》</text>与<text class="font-blue" @click="toggle2('bottom')">《隐私政策》</text></view>
					</view>
				</label>
			</radio-group>
		</view>
	</view>
</template>
<script>
	// 在页面中导入相关 api
	// import {validstr,subStr} from '@/utils/validate';
	import {getservice_agreement,getprivacy_agreement,shopemployeelogin,userget_app_id,userwxlogin} from "@/api/apiinfo";
	export default {
		data() {
			return {
				userphone: '',
				password:'',
				isWeixin:false,
				getcodeurl:'',
				appid:'',
				isnamelogin:1,
				readitem:false,
				service_txt:'',
				privacy_txt:'',
				type:'',
				shopid:0,
			}
		},
		mounted() { ////////////////// uni组件样式重定义
			// var str = document.getElementsByClassName("uni-h1");
			// Array.prototype.forEach.call(str, function(h1){
			// 	h1.style.fontWeight = "normal";
			// });
		},
		// 页面销毁前移除监听
		onUnload() {
		   // window.removeEventListener('popstate', this.onBackButtonEvent, false);
		},
		onLoad() {
			this.disableBackButton();
			// localStorage.setItem('userToken', '60815b65-9b66-480e-a447-dee164c6f0fd');//需要删除 
			// localStorage.setItem('mobile', '13295458250');//需要删除 
			// console.log("登录页商户ID："+this.$route.query.id)
			// this.shopid = this.$route.query.id;
			// this.shopid = 51//需要删除
			// localStorage.setItem('shopid', this.shopid);
			
			// const hasWechatLogin = uni.getStorageSync('wechat_login_tag') || null;
			// if (hasWechatLogin) {
			// 	uni.removeStorageSync('wechat_login_tag');
			// 	// this.checkWeChatCode();
			// }
			
			//this.isWeixin = this.isWechat()
			//if (this.isWeixin) {				
			//	this.checkWeChatCode() //通过微信官方接口获取code之后，会重新刷新设置的回调地址【redirect_uri】
			//}
			
			let logined = uni.getStorageSync('userToken')
			console.log('token:'+logined)
			// if(logined == null || logined === undefined || logined == ''){
			if(logined == null || typeof logined === 'undefined' || logined == 'undefined' || logined == ''){
				// if(this.appid == null || this.appid === undefined || this.appid == ''){
					//this.usergetappid() //获取appid
				// }				
			}else{
				console.log(logined.length)
				if(logined.length > 30){
					var getTimestamp=new Date().getTime();
					uni.switchTab({ //底部导航跳转方式
						url: '/pages/shop/shop?timestamp='+getTimestamp
					});
				}
			}
			
			this.getservice_agreementinfo()//用户服务协议
			this.getprivacy_agreementinfo()//用户隐私协议
			
		}, 
		methods: {
			getprivacy_agreementinfo(){ //用户隐私协议
				getprivacy_agreement().then((res) => {
					console.log("用户隐私协议接口返回数据：")
					console.log(JSON.stringify(res));
					this.privacy_txt = res.data.content
				}).catch(err => {
					// console.log(JSON.stringify(err))
					uni.showModal({
						title: '提示',
						content: '用户隐私协议报错：'+err.errMsg,
						showCancel: false,
						success: function (res) {
							if (res.confirm) {
								// uni.switchTab({ //内部页面跳转方式
								// 	url: '/pages/shop/shop'
								// })
							} 
						}
					});
				})
			},
			getservice_agreementinfo(){ //用户服务协议				
				getservice_agreement().then((res) => {
					console.log("用户服务协议接口返回数据：")
					console.log(JSON.stringify(res));
					this.service_txt = res.data.content
				}).catch(err => {
					// console.log(JSON.stringify(err))
					uni.showModal({
						title: '提示',
						content: '用户服务协议报错：'+err.errMsg,
						showCancel: false,
						success: function (res) {
							if (res.confirm) {
								// uni.switchTab({ //内部页面跳转方式 
								// 	url: '/pages/shop/shop'
								// })
							} 
						}
					});
				})
			},
			toggle(type) {
				this.type = type
				// open 方法传入参数 等同在 uni-popup 组件上绑定 type属性
				this.$refs.popup.open(type)
			},
			toggle2(type) {
				this.type = type
				// open 方法传入参数 等同在 uni-popup 组件上绑定 type属性
				this.$refs.popup2.open(type)
			},
			changeradio(e){
				this.readitem = !this.readitem
			},			
			disableBackButton() {
			    // 在history中记录当前位置或者一个空页面
			    // history.pushState(null, null, location.href);
			    // window.addEventListener('popstate', this.onBackButtonEvent, false);
			  },
			  onBackButtonEvent(event) {
			    // 当用户点击返回键时，阻止默认行为
			    event.preventDefault();
			    // 可以在这里添加你想要执行的代码，比如返回上一个页面或者做其他操作
			  },
			usergetappid(){
				// if(this.shopid == '' || this.shopid == null){
				// 	uni.showModal({
				// 		title: '提示',
				// 		content: '获取商户id出错，请重新打开页面或联系管理员！',
				// 		showCancel: false,
				// 		success: function (res) {
				// 			if (res.confirm) {
				// 				// uni.switchTab({ //内部页面跳转方式 
				// 				// 	url: '/pages/shop/shop'
				// 				// })
				// 			} 
				// 		}
				// 	});
				// 	return false
				// }
				userget_app_id().then((res) => {
					console.log("userget_app_id接口返回数据：")
					console.log(JSON.stringify(res));
					this.appid = res.data;
					let appid = this.appid;
					let local = encodeURIComponent(window.location.href); //获取当前页面地址作为回调地址${local}
					this.getcodeurl = 'https://open.weixin.qq.com/connect/oauth2/authorize?appid='+appid+'&redirect_uri='+local+'&response_type=code&scope=snsapi_userinfo&state=STATE&connect_redirect=1#wechat_redirect';
					window.location.href = this.getcodeurl;//直接跳页
					console.log(this.getcodeurl)
				}).catch(err => {
					// console.log(JSON.stringify(err))
					uni.showModal({
						title: '提示',
						content: '获取appid报错：'+err.errMsg,
						showCancel: false,
						success: function (res) {
							if (res.confirm) {
								// uni.switchTab({ //内部页面跳转方式 
								// 	url: '/pages/shop/shop'
								// })
							} 
						}
					});
				})
			},
			wxlogin(){
				var that = this
				if(!this.readitem){
					uni.showModal({
						content: '请选择我已阅读《相关条约》',
						showCancel: false,
					});
					return false
				}
				uni.setStorageSync('wechat_login_tag', 'true');
				
				uni.login({
				        provider: 'weixin',
				        success: function (loginRes) {
							that.login_codewx = loginRes.code
							that.code = loginRes.code
				        	//	打印临时凭证
				        	console.log(loginRes.code)
							uni.setStorageSync('wxcode', loginRes.code);
							that.touserwxlogin()
				    	}
				});
				// 登录成功
				// uni.getUserInfo({
				//     provider: 'weixin',
				//     success: function(info) {
				// 		console.log(JSON.stringify(info))
				//         // 获取用户信息成功, info.authResult是用户信息
				//         const wxUserInfo = info.userInfo
				// 		//	打印头像url
				//         console.log(wxUserInfo.avatarUrl)
				//         //	打印昵称
				//         console.log(wxUserInfo.nickName)
				//         //	打印用户详细信息
				//         console.log(wxUserInfo)
				//     }
				// })
				
				
				// this.usergetappid() //获取appid
				
				///let code = this.getUrlCode().code
				
				// let storagecode = localStorage.getItem('wxusercode')
				// console.log("缓存code："+storagecode)
				// if(storagecode){//是否已经登录并存在code
				// 	if(code == storagecode){//如果存在并一样的话则清空，执行下面的重定向，
				// 		code = null
				// 	}else{//如果存在但一样的话测存储起来
				// 		localStorage.setItem('wxusercode', code);
				// 	}
				// }else{//第一次登录不存在code则存起来
				// 	localStorage.setItem('wxusercode', code);
				// }
				// console.log("缓存code判断以后："+localStorage.getItem('wxusercode'))
				///this.code = code
				//如果没有code 去获取code
				///console.log('是否存在code:'+code)
				
				/*
				if (code == null || typeof code === 'undefined' || code == '') {
					window.location.href = this.getcodeurl;
				}else{
					//获取到code后的逻辑 
					this.touserwxlogin()
				}
				*/
			},
			touserwxlogin(){
				console.log("微信登录code："+this.code)
				if(this.code){
					userwxlogin(this.code,'app').then((res) => {
						console.log("userwxlogin接口返回数据：");
						console.log(JSON.stringify(res));
						// localStorage.setItem('userToken', res.data.token);
						// localStorage.setItem('userId', res.data.id);
						// localStorage.setItem('username', res.data.realname);
						// localStorage.setItem('nickname', res.data.nickname);
						// localStorage.setItem('avatar', res.data.avatar);
						// localStorage.setItem('openid', res.data.openid);
						// localStorage.setItem('mobile', res.data.mobile);
						// localStorage.setItem('province', JSON.stringify(res.data.province));
						// localStorage.setItem('city', JSON.stringify(res.data.city));
						
						uni.setStorageSync('userToken', res.data.token);
						uni.setStorageSync('userId', res.data.id);
						uni.setStorageSync('username', res.data.realname);
						uni.setStorageSync('nickname', res.data.nickname);
						uni.setStorageSync('avatar', res.data.avatar);
						uni.setStorageSync('openid', res.data.openid);
						uni.setStorageSync('mobile', res.data.mobile);
						uni.setStorageSync('province', JSON.stringify(res.data.province));
						uni.setStorageSync('city', JSON.stringify(res.data.city));
						
						console.log('参数')
						console.log(res.data.token)
						
						 // if(res.data.mobile != ''){
							 var getTimestamp=new Date().getTime();
							 uni.switchTab({ //底部导航跳转方式
							 	url: '/pages/shop/shop?timestamp='+getTimestamp
							 });
						 // }else{
						 	// var getTimestamp=new Date().getTime();
						 	// uni.navigateTo({ //底部导航跳转方式
						 	// 	url: '/pages/shop/bind_phone?timestamp='+getTimestamp
						 	// });
						 // }
					}).catch(err => {
						console.log("登录报错：")
						console.log(JSON.stringify(err))
						if(err.errMsg){
							uni.showModal({
								title: '提示',
								content: '登录报错：'+err.errMsg,
								showCancel: false,
								success: function (res) {
									if (res.confirm) {
										// uni.switchTab({ //内部页面跳转方式 
										// 	url: '/pages/shop/shop_admin'
										// })
									} 
								}
							});
						}
						
					})
				}
			},
			
			// 是否为微信浏览器
			isWechat() {
				return String(navigator.userAgent.toLowerCase().match(/MicroMessenger/i)) === "micromessenger";
			},
			//检查浏览器地址栏中微信接口返回的code 
			checkWeChatCode() {
				let current_code = this.getUrlCode().code
				if (current_code == null || typeof current_code === 'undefined') {
					return false;
				}
				this.code = current_code
				//localStorage.setItem('wxcode', this.code);
				console.log("获取到的code:"+current_code)
				if (this.code) {
					this.touserwxlogin()
				}
				
				// let current_code = this.getUrlCode().code
				
				// if (current_code == null || typeof current_code === 'undefined') {
				// 	return false;
				// }
				// this.code = current_code
				
				// let storagecode = localStorage.getItem('wxusercode')
				// console.log('当前code:'+current_code)
				// console.log("缓存code："+storagecode)
				// if(storagecode){//是否已经登录并存在code
				// 	if(current_code == storagecode){//如果存在并一样的话则清空，执行下面的重定向，
				// 		current_code = null
				// 	}else{//如果存在但不一样的话测存储起来
				// 		localStorage.setItem('wxusercode', current_code);
				// 		this.touserwxlogin()
				// 	}
				// }else{//第一次登录不存在code则存起来
				// 	localStorage.setItem('wxusercode', current_code);
				// 	this.touserwxlogin()
				// }
				
			},
			
			
			//截取code
			getUrlCode() {
				var url = location.search;
				var theRequest = new Object();
				if (url.indexOf("?") !== -1) {
				  var str = url.substr(1)
				  var strs = str.split("&");
				  for (var i = 0; i < strs.length; i++) {
					theRequest[strs[i].split("=")[0]] = (strs[i].split("=")[1])
				  }
				}
				console.log(theRequest)
				return theRequest;
				// let test = {code: "011IKK000MgsMS1MWJ300mhTnt2IKK01", state: "STATE"}				
				// return test;
			  },


		}
	}
</script>

<style lang="scss">
	.content{
		padding: 100rpx 30rpx;
		.fixed-btn{
			// position: fixed;
			position: absolute;
			bottom: 140rpx;
			right: 30rpx;
			left: 30rpx;
		}
	}
	.login{
		height: 1300rpx;
		button{
			border-radius: 40rpx;
			margin-bottom: 30rpx;
			font-size: 32rpx;
		}
		.policy-text{
			align-items: center;
			justify-content: center;
			font-size: 28rpx;
			color: #999;
			.font-blue{
				color:#4371FA;
			}
			.font-baise{
				color:#ffffff;
			}
		}
	}
	
	@mixin flex {
		/* #ifndef APP-NVUE */
		display: flex;
		/* #endif */
		flex-direction: row;
	}
	.popup-content {
		@include flex;
		align-items: top;
		justify-content: top;
		padding: 15px;
		height: 500px;
		overflow-y: auto;
		font-size: 12px;
		background-color: #fff;
	}
	page{
		// background: #e71f2c url("/static/img/login_bg.png") no-repeat center 35%;
		// background-size: 90%;
		background:#e71f2c url("https://m.qpic.cn/psc?/89b9a87a-bf34-461a-b3f4-c9d87dfe5e02/LiySpxowE0yeWXwBdXN*SVZOWtxLGHPcaGTPbNDjjW02YH9LeBIT7VyzV28BRVoIBf1X.iM97QZYoJ256fw9KeBVaRNQ6F1g73Kep.FOD1A!/b&bo=xwKrA8cCqwMDByI!&rf=viewer_4") no-repeat center 50%;
		background-size: 90%;
	}
</style>